<template>
	<view class="container">
		<!-- 订单基本信息 -->
		<view class="order-basic-info">
			<view class="order-header">
				<text class="order-no">订单号：{{ orderInfo.order_no }}</text>
				<view class="status-badge" :class="getStatusClass[orderInfo.state]">
					{{ getStatusText(orderInfo.state) }}
				</view>
			</view>
		</view>

		<!-- 配货信息表单 -->
		<view class="delivery-form">
			<!-- 寄件地址信息 -->
			<view class="form-item">
				<text class="form-label">寄件地址</text>

				<!-- 省份选择 -->
				<view class="address-select">
					<view class="select-item">
						<text class="select-label">省份</text>
						<picker @change="onProvinceChange" :value="provinceIndex" :range="provinces" range-key="name">
							<view class="picker">
								{{ provinces[provinceIndex].name || '请选择省份' }}
							</view>
						</picker>
					</view>

					<!-- 城市选择 -->
					<view class="select-item">
						<text class="select-label">城市</text>
						<picker @change="onCityChange" :value="cityIndex" :range="cities" range-key="name"
							:disabled="!provinceId">
							<view class="picker" :class="{ disabled: !provinceId }">
								{{ cities[cityIndex].name || '请选择城市' }}
							</view>
						</picker>
					</view>

					<!-- 区县选择 -->
					<view class="select-item">
						<text class="select-label">区县</text>
						<picker @change="onAreaChange" :value="areaIndex" :range="areas" range-key="name"
							:disabled="!cityId">
							<view class="picker" :class="{ disabled: !cityId }">
								{{ areas[areaIndex].name || '请选择区县' }}
							</view>
						</picker>
					</view>
				</view>

				<!-- 详细地址 -->
				<view class="detail-address">
					<uv-textarea v-model="deliveryAddress" placeholder="请输入详细地址（街道、门牌号等）" border="none"
						:customStyle="{ padding: '20rpx', background: '#f8f9fa', borderRadius: '12rpx', fontSize: '28rpx', marginTop: '20rpx' }">
					</uv-textarea>
				</view>
			</view>

			<!-- 配货凭证上传 -->
			<view class="form-item">
				<text class="form-label">配货凭证</text>
				<text class="form-tip">（最多上传6张图片）</text>

				<view class="upload-section">
					<wanl-upload v-model="imageList" :maxCount="6" :multiple="true" uploadText="上传凭证"
						tipText="支持jpg、png格式，大小不超过2M" @upload-success="onUploadSuccess" @upload-error="onUploadError"
						@delete="onImageDelete"></wanl-upload>
				</view>
			</view>

			<view class="form-item">
				<text class="form-label">备注</text>

				<view class="detail-address">
					<uv-textarea v-model="remark" border="none" disabled
						:customStyle="{ padding: '20rpx', background: '#f8f9fa', borderRadius: '12rpx', fontSize: '28rpx', marginTop: '20rpx' }">
					</uv-textarea>
				</view>
			</view>

		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-actions">
			<view class="action-btn confirm" :class="{ disabled: !canSubmit }" @click="handleSubmit">
				确认配货
			</view>
		</view>

		<!-- 加载中 -->
		<uv-loading-icon v-if="loading" text="提交中..." mode="circle" size="36"></uv-loading-icon>
	</view>
</template>

<script>
	import wanlUpload from '@/components/wanl-upload/wanl-upload.vue';
	export default {
		components: {
			wanlUpload
		},
		data() {
			return {
				orderId: null,
				loading: false,
				orderInfo: {
					order_no: '',
					state: ''
				},
				// 地址相关数据
				provinceId: '',
				cityId: '',
				areaId: '',
				deliveryAddress: '',
				provinceIndex: 0,
				cityIndex: 0,
				areaIndex: 0,
				provinces: [],
				cities: [],
				areas: [],
				imageList: [],
				areaData: [],
				remark: '客户选择平台物流下单，请确认发货地址，点击确定即预约物流上门！'
			};
		},
		computed: {
			canSubmit() {
				return this.provinceId && this.cityId && this.areaId &&
					this.deliveryAddress.trim() !== '' &&
					this.imageList.length > 0;
			}
		},
		onLoad(options) {
			if (options.id) {
				this.orderId = options.id;
				this.loadOrderDetail();
			} else {
				this.$wanlshop.msg('订单ID不存在');
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		},
		onBackPress() {
			// 拦截返回按钮，直接返回
			uni.navigateBack();
			return true;
		},
		methods: {
			// 加载订单详情
			async loadOrderDetail() {
				this.loading = true;
				try {
					const res = await uni.$uv.http.get('/supplier/getOrderDetail', {
						params: {
							order_id: this.orderId
						}
					});

					if (res.res.code === 1) {
						const data = res.res.data;
						this.orderInfo = data;
						this.loadRegionData();
					} else {
						this.$wanlshop.msg(res.res.msg || '获取订单详情失败');
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				} catch (error) {
					console.error('获取订单详情失败:', error);
					this.$wanlshop.msg('获取订单详情失败');
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} finally {
					this.loading = false;
				}
			},
			// 加载地区数据
			async loadRegionData() {
				try {
					const res = await uni.$uv.http.get('/wanlshop/common/area');
					if (res.res.code === 1) {
						this.areaData = res.res.data || [];
						this.provinces = res.res.data || [];

						// 如果有订单的省市ID，设置默认选中
						if (this.orderInfo.province_id && this.orderInfo.city_id) {
							await this.setDefaultAddress(this.orderInfo.province_id, this.orderInfo.city_id);
						} else {
							// 如果没有默认地址，初始化第一个省份的城市和区县
							await this.initFirstProvince();
						}
					} else {
						this.$wanlshop.msg('加载省份数据失败');
					}
				} catch (error) {
					console.error('加载地区数据失败:', error);
					this.$wanlshop.msg('加载地区数据失败');
				}
			},

			// 设置默认地址
			async setDefaultAddress(provinceId, cityId) {
				const provinceIndex = this.provinces.findIndex(item => item.id == provinceId);
				if (provinceIndex === -1) {
					console.warn('未找到对应的省份，使用第一个省份');
					await this.initFirstProvince();
					return;
				}

				this.provinceIndex = provinceIndex;
				this.provinceId = provinceId;

				// 设置城市数据
				this.cities = this.provinces[provinceIndex].city || [];

				const cityIndex = this.cities.findIndex(item => item.id == cityId);
				if (cityIndex === -1) {
					console.warn('未找到对应的城市，使用第一个城市');
					this.cityIndex = 0;
					this.cityId = this.cities[0]?.id || '';
				} else {
					this.cityIndex = cityIndex;
					this.cityId = cityId;
				}

				// 设置区县数据
				await this.setAreaData();
			},

			// 初始化第一个省份的数据
			async initFirstProvince() {
				if (this.provinces.length === 0) return;

				this.provinceIndex = 0;
				this.provinceId = this.provinces[0].id;
				this.cities = this.provinces[0].city || [];

				if (this.cities.length > 0) {
					this.cityIndex = 0;
					this.cityId = this.cities[0].id;
					await this.setAreaData();
				}
			},

			// 设置区县数据
			async setAreaData() {
				if (this.cities.length === 0 || this.cityIndex >= this.cities.length) {
					this.areas = [];
					this.areaId = '';
					this.areaIndex = 0;
					return;
				}

				this.areas = this.cities[this.cityIndex].area || [];

				if (this.areas.length > 0) {
					this.areaIndex = 0;
					this.areaId = this.areas[0].id;
				} else {
					this.areaId = '';
					this.areaIndex = 0;
				}
			},

			// 省份选择变化
			async onProvinceChange(e) {
				const index = e.detail.value;
				if (index === this.provinceIndex) return;

				this.provinceIndex = index;
				this.provinceId = this.provinces[index]?.id || '';

				// 重置城市和区县
				this.cityId = '';
				this.areaId = '';
				this.cityIndex = 0;
				this.areaIndex = 0;
				this.cities = [];
				this.areas = [];

				if (this.provinceId && this.provinces[index]) {
					// 加载城市数据
					this.cities = this.provinces[index].city || [];

					if (this.cities.length > 0) {
						this.cityId = this.cities[0].id;
						await this.setAreaData();
					}
				}
			},

			// 城市选择变化
			async onCityChange(e) {
				const index = e.detail.value;
				if (index === this.cityIndex) return;

				this.cityIndex = index;
				this.cityId = this.cities[index]?.id || '';

				// 重置区县
				this.areaId = '';
				this.areaIndex = 0;
				this.areas = [];

				if (this.cityId) {
					await this.setAreaData();
				}
			},

			// 区县选择变化
			onAreaChange(e) {
				const index = e.detail.value;
				this.areaIndex = index;
				this.areaId = this.areas[index]?.id || '';
			},

			// 上传成功回调
			onUploadSuccess(event) {
				console.log('上传成功:', event);
				const {
					file,
					result,
					index
				} = event;
				this.$wanlshop.msg('上传成功');
			},

			// 上传失败回调
			onUploadError(event) {
				console.error('上传失败:', event);
				const {
					file,
					error,
					index
				} = event;
				this.$wanlshop.msg('上传失败: ' + (error.message || '未知错误'));
			},

			// 删除图片回调
			onImageDelete(event) {
				console.log('删除图片:', event);
				const {
					file,
					index
				} = event;
				this.$wanlshop.msg('删除成功');
			},

			// 获取状态文本
			getStatusText(state) {
				const statusMap = {
					'1': '待付款',
					'2': '待发货',
					'3': '待收货',
					'4': '已收货',
					'5': '已评价',
					'6': '已完成',
					'7': '已取消'
				};
				return statusMap[state] || '未知状态';
			},

			// 获取状态类名
			getStatusClass(state) {
				const classMap = {
					'1': 'status-pending',
					'2': 'status-wait-ship',
					'3': 'status-wait-receive',
					'4': 'status-received',
					'5': 'status-evaluated',
					'6': 'status-completed',
					'7': 'status-cancelled'
				};
				return classMap[state] || 'status-default';
			},

			// 提交配货
			async handleSubmit() {
				if (!this.canSubmit) {
					this.$wanlshop.msg('请完善寄件地址信息并上传配货凭证');
					return;
				}

				// 验证详细地址
				if (this.deliveryAddress.trim().length < 5) {
					this.$wanlshop.msg('请输入完整的详细地址');
					return;
				}

				uni.showModal({
					title: '确认配货',
					content: `确定要对订单 ${this.orderInfo.order_no} 进行配货吗？`,
					success: async (res) => {
						if (res.confirm) {
							await this.submitExpressOrder();
						}
					}
				});
			},

			// 提交配货请求
			async submitExpressOrder() {
				this.loading = true;

				try {
					// 获取图片URL数组
					const images = this.imageList.map(item => item.url).join(',');
					const res = await uni.$uv.http.post('/supplier/expressOrder', {
						order_id: this.orderId,
						province_id: this.provinceId,
						city_id: this.cityId,
						area_id: this.areaId,
						delivery_address: this.deliveryAddress,
						images: images
					});

					if (res.res.code === 1) {
						this.$wanlshop.msg('配货成功');

						// 显示生成的快递单号（如果有）
						if (res.res.data && res.res.data.express_no) {
							setTimeout(() => {
								this.$wanlshop.msg(`系统已生成快递单号：${res.res.data.express_no}`);
							}, 500);
						}

						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						this.$wanlshop.msg(res.res.msg || '配货失败');
					}
				} catch (error) {
					console.error('配货失败:', error);
					this.$wanlshop.msg('配货失败，请稍后重试');
				} finally {
					this.loading = false;
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
		background-color: #f5f7fa;
		min-height: 100vh;
		box-sizing: border-box;
		padding-bottom: 140rpx;
	}

	/* 订单基本信息 */
	.order-basic-info {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.order-no {
				font-size: 28rpx;
				font-weight: 600;
				color: #333;
			}

			.status-badge {
				padding: 8rpx 16rpx;
				border-radius: 20rpx;
				font-size: 22rpx;
				font-weight: 500;

				&.status-wait-ship {
					background: #e8f3ff;
					color: #2979ff;
				}
			}
		}
	}

	/* 配货信息表单 */
	.delivery-form {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

		.form-item {
			margin-bottom: 40rpx;

			.form-label {
				display: block;
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
				margin-bottom: 16rpx;
			}

			.form-tip {
				font-size: 24rpx;
				color: #999;
				margin-left: 12rpx;
			}

			.address-select {
				.select-item {
					margin-bottom: 20rpx;

					.select-label {
						display: block;
						font-size: 26rpx;
						color: #666;
						margin-bottom: 10rpx;
					}

					.picker {
						padding: 20rpx;
						background: #f8f9fa;
						border-radius: 12rpx;
						font-size: 28rpx;
						color: #333;

						&.disabled {
							background: #f0f0f0;
							color: #999;
						}
					}
				}
			}
		}

		.upload-section {
			margin-top: 20rpx;

			// 覆盖 wanl-upload 组件的样式
			.wanl-upload {
				.upload-area {
					.upload-custom {
						width: 160rpx !important;
						height: 160rpx !important;
					}
				}

				.preview-container {
					.image-list {
						.image-item {
							width: 160rpx !important;
							height: 160rpx !important;
						}
					}
				}
			}
		}
	}

	/* 底部操作栏 */
	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #ffffff;
		padding: 20rpx 30rpx;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
		z-index: 999;

		.action-btn {
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 40rpx;
			font-size: 30rpx;
			font-weight: 500;

			&.confirm {
				background: #2979ff;
				color: #ffffff;

				&.disabled {
					background: #ccc;
					color: #999;
				}
			}
		}
	}
</style>